<?php
namespace adminv1\auth; 
use adminv1\CoreController;
use Yii;
use admin\models\auth\Roles;
use admin\models\auth\AuthApi;

/*
	用户角色相关控制器
*/

class RoleController extends CoreController
{
    protected function getModelClass(): string
    {
        return Roles::class;
    }

	//角色列表
	public function actionRoleList()
	{
		$roleList = Roles::getRoles($this->_user);
		return $this->success('角色列表',$roleList);
	}

	/*角色添加 修改*/
	public function actionRoleEdit()
	{
		$role = new Roles;
		$params = $this->request;
		if($id = $this->request('id')){
			$role = $role::findOne($id);
		}else{
			$params['create_time'] = $this->curDateTime;
			$params['uid'] = $this->_uid;
		}	

		try{
			if($role->load($params,'') && $role->validate() == true && $role->save())
			{	
				return $this->success('操作成功',$role->attributes);
			}
			$errMsg = $authRule::outError($authRule->getErrors());
			return $this->error($errMsg['msg']);
			
		}catch(\Exception $e)
		{
			return $this->error($e->getMessage());
		}
		
	}

	//删除
	public function actionRoleDel()
	{
		if(!$id = $this->request('id'))
			return $this->error('参数错误');

		$where = ['id'=>$id];
		$res = Roles::deleteAll($where);
		if($res) return $this->success('删除成功');
		return $this->error('删除失败');

	}


	//获取角色对应的权限菜单
	//id 角色ID
	public function actionRoleAuthList()
	{
		$roleId   = $this->request('id');
		$authData = Roles::showRoleAuth($roleId);
		return $this->success('角色权限列表',$authData);
	}

	/*
		修改角色权限
		auth string 角色的权限集 形如 3,23,24
 	*/
	public function actionRoleAuthEdit()
	{
		$authIds = $this->request('auths');
		if(!$roleId = $this->request('id')){
			return $this->error('参数错误');
		} 
		$authIds = json_decode($authIds,true);
		$ruleIds = $apiIds = []; 
		foreach($authIds as $id)
		{
			if($id < 20000) $ruleIds[] = $id;
			if($id >= 20000) $apiIds[] = $id;
		}



		if($apiIds)
		{
			foreach($apiIds as $apiId)
			{
				$api = AuthApi::findOne(['id' => $apiId]);
				if(!in_array($api->rule_id, $ruleIds)) $ruleIds[] = $api->rule_id;
			}
		}
		
		$ruleIds = implode(',', $ruleIds);
		$apiIds = implode(',', $apiIds);
		
		$flag = Roles::editRoleAuth($roleId,[
			'rule_ids' => $ruleIds, 
			'api_ids' => $apiIds,
			'update_time'=> date("Y-m-d H:i:s")
		]);
		if($flag) return $this->success('操作成功');
		return $this->error('操作失败');
	}

}